<?php

require_once "include.php";

if($method == "GET"){
	$query = "SELECT * FROM comment";

	if($_REQUEST["user_id"]){
		$ids = explode(",", $_REQUEST['user_id']);

		$i = 0;
		foreach($ids as $id){
			if($i == 0){
				if($_REQUEST["type"]){
					$type = $_REQUEST["type"];
					$query .= " WHERE type=$type AND user_id=$id ORDER BY id DESC";
				} else{
					$query .= " WHERE user_id=$id ORDER BY id DESC";
				}
			} else{
				$query .= " OR user_id=$id ORDER BY id DESC";
			}

			$i++;
		}
	}
	else if($_REQUEST["to_id"]){
		$id = mysql_real_escape_string($_REQUEST['to_id']);
		$type = mysql_real_escape_string($_REQUEST["type"]);

		$query .= " WHERE type=$type AND to_id=$id ORDER BY id DESC";	
	}

	$result = mysql_query($query) or die(mysql_error());  

	$return_arr = array();

	while($row = mysql_fetch_array( $result )){
		$comment = array(
					"id" => $row["id"],
					"type" => $row["type"],
					"comment" => $row["comment"],
					"rating" => $row["rating"],
					"user_id" => $row["user_id"],
					"to_id" => $row["to_id"]
					);

		$return_arr[] = $comment;
	}

	echo json_encode($return_arr);	
}
else if($method == "POST"){
	$type = mysql_real_escape_string($_REQUEST['type']);
	$comment = mysql_real_escape_string($_REQUEST['comment']);
	$user_id = mysql_real_escape_string( $_REQUEST['user_id'] );
	$to_id = mysql_real_escape_string( $_REQUEST['to_id'] );
	$rating = mysql_real_escape_string( $_REQUEST['rating'] );
	
	if($type && $comment && $user_id && $to_id){
		if(!$rating){
			$rating = 0;
		}
		$query = "INSERT INTO comment(type, comment, rating, user_id, to_id) VALUES($type, '$comment', $rating, $user_id, $to_id)";

		$result = mysql_query($query);
		if($result){
			echo json_encode(array("result" => "successful"));
		}else{
			echo json_encode(array("result" =>  mysql_error()));
		}
	}
}
else if($method == "DELETE"){
	if($_REQUEST["id"]){
		$id = mysql_real_escape_string($_REQUEST["id"]);
		$query = "DELETE FROM comment WHERE id=$id";
		
		$result = mysql_query($query);
		if($result){
			echo json_encode("true");
		}else{
			$error = array("error" =>  mysql_error());
			echo json_encode($error);
		}
	}
}

?>